﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
using System.Data;

namespace Site.Mobile
{
    public partial class Admin : System.Web.UI.Page
    {
        public string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string sUser = Request.QueryString["User"];
            string sPass = Request.QueryString["ID"];

            if (sUser == null || sPass == null)
            {
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "text/plain";
                Response.Write("400 Bad Request");
                Response.End();
                return;
            }

            sPass = CalculateMD5Hash(sPass);

            SqlDataSource1.SelectCommand = "SELECT * FROM Users WHERE User_Name='" + sUser + "' AND Password='" + sPass + "'";
            DataSourceSelectArguments Select = new DataSourceSelectArguments();
            DataView View = (DataView)SqlDataSource1.Select(Select);

            if (View.Count == 1)
            {
                Session["userID"] = View[0]["User_Name"].ToString();
                Session["userType"] = View.Table.Rows[0]["User_Type"].ToString();
            }
            else
            {
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "text/plain";
                Response.Write("401 Unauthorized");
                Response.End();
            }
        }
    }
}